<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline" @submit.prevent>
      <el-form-item label="所属项目" style="width: 220px">
        <el-select
            v-model="queryParams.projectId"
            placeholder="请选择所属项目"
            clearable
            filterable
            style="width: 100%"
        >
          <el-option
              v-for="item in uniqueProductList"
              :key="item.id"
              :label="item.projectName"
              :value="item.projectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品名称" style="width: 220px">
        <el-input v-model="queryParams.name" placeholder="请输入产品名称" clearable/>
      </el-form-item>
      <el-form-item label="产品类型" style="width: 220px">
        <el-select v-model="queryParams.type" placeholder="请选择产品类型" clearable style="width: 100%">
          <el-option label="HIC" value="HIC"/>
          <el-option label="高硅氧" value="高硅氧"/>
          <el-option label="涂层" value="涂层"/>
          <el-option label="结构复材" value="结构复材"/>
          <el-option label="电气" value="电气"/>
          <el-option label="力热" value="力热"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchProductList">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button v-if="isAdmin" type="primary" @click="openAddDialog">添加产品</el-button>
        <el-button v-if="isAdmin" type="primary" @click="dialogVisible = true">导入产品</el-button>
      </el-form-item>
    </el-form>
    <!-- 导入弹窗 -->
    <!-- 导入弹窗 -->
    <el-dialog v-model="dialogVisible" title="导入产品" width="420px">
      <!-- 产品类型选择 -->
      <el-form :model="importForm" label-width="80px" style="margin-bottom: 10px;">
        <el-form-item label="产品类型" required>
          <el-select v-model="importForm.productType" placeholder="请选择产品类型" style="width: 100%;">
            <el-option label="HIC" value="HIC"/>
            <el-option label="高硅氧" value="高硅氧"/>
            <el-option label="涂层" value="涂层"/>
            <el-option label="结构复材" value="结构复材"/>
            <el-option label="电气" value="电气"/>
            <el-option label="力热" value="力热"/>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 上传文件 -->
      <el-upload
          ref="uploadRef"
          :file-list="fileList"
          :auto-upload="false"
          :before-upload="beforeUpload"
          accept=".xlsx"
          :limit="1"
          :on-change="handleFileChange"
          :disabled="!importForm.productType"
      >
        <el-button type="primary" :disabled="!importForm.productType">选择 Excel 文件</el-button>
        <div style="margin-top: 10px; font-size: 12px; color: #999;">
          仅支持 .xlsx 文件
        </div>
      </el-upload>

      <!-- 下载模板 -->
      <el-button
          type="success"
          style="margin-top: 10px;"
          @click="downloadTemplate"
          :disabled="!importForm.productType"
      >
        下载导入模板
      </el-button>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitImport">确定导入</el-button>
      </template>
    </el-dialog>

    <!-- 表格 -->
    <Table
        :projectList="productList"
        :columns="columns"
        :queryParams="queryParams"
        :total="total"
        :loading="loading"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        @update="handleUpdate"
        @remove="handleRemove"
        @detail="handleDetail"
    >
      <template #operate="{ row }">
        <el-button type="primary" link @click="openGantt(row)">甘特图</el-button>
      </template>
    </Table>

    <!-- 编辑弹窗 -->
    <FormDialog
        v-model:visible="editDialogVisible"
        width="400"
        :model="currentRow"
        :columns="Columns"
        :title="dialogTitle"
        :okText="okButtonText"
        formWidth="350px"
        @save="handleSave"
    />

    <!-- 甘特图弹窗 -->
    <div v-if="ganttPram.show">
      <GanttDialog :pram="ganttPram" @update="fetchProductList"/>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed, reactive} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'
import Table from '@/components/el-table/Table.vue'
import FormDialog from '@/components/FormDialog/FormDialog.vue'
import GanttDialog from "@/views/product/GanttDialog.vue";

import {useRoute} from 'vue-router'

const route = useRoute()
import {useAuthStore} from '@/stores/auth.js'


const api = axios.create({
  // baseURL: "https://pro.lkkj.xyz",
  baseURL: "http://localhost:8080",
  timeout: 50000,
})

const authStore = useAuthStore()

const isAdmin = computed(() => {
  return authStore.token === 'admin'
})

const queryProParams = ref({
  code: '',
  name: '',
  clientUsername: authStore.token,
  client: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

const dialogTitle = computed(() => {
  return currentRow.value.id ? '编辑产品信息' : '新增产品'
})

const okButtonText = computed(() => {
  return currentRow.value.id ? '保存' : '新增'
})


const productList = ref([])

const projectList = ref([])

const uniqueProductList = ref([])
const total = ref(0)
const loading = ref(false)
const currentRow = ref({})
const editDialogVisible = ref(false)

const columns = [
  {prop: 'projectName', label: '所属项目', minWidth: 120},
  {prop: 'name', label: '产品名称', minWidth: 120},
  {prop: 'type', label: '产品类型', minWidth: 120},
  {label: '进度', minWidth: 120, isProgress: true},
  {prop: 'amount', label: '产品总数', minWidth: 120},
  {prop: 'finishAmount', label: '完成数量', minWidth: 120},
]

const Columns = ref([{
  prop: 'projectId',
  label: '所属项目',
  type: 'select',
  options: [],
},
  {prop: 'name', label: '产品名称', type: 'text'},
  {
    prop: 'type',
    label: '产品类型',
    type: 'select',
    options: [
      {label: 'HIC', value: 'HIC'},
      {label: '高硅氧', value: '高硅氧'},
      {label: '涂层', value: '涂层'},
      {label: '结构复材', value: '结构复材'},
      {label: '电气', value: '电气'},
      {label: '力热', value: '力热'},
    ]
  },
  {prop: 'amount', label: '产品总数', type: 'text'},
  {prop: 'finishAmount', label: '完成数量', type: 'text'},])


const projectId = ref(route.query.projectId || '')

const queryParams = ref({
  projectId: projectId.value,
  clientUsername: authStore.token,
  name: '',
  type: '',
  process: '',
  pageNum: 1,
  pageSize: 10,
})

// 甘特图弹窗参数
const ganttPram = reactive({show: false, data: {}})

// 打开甘特图
const openGantt = (row) => {
  ganttPram.show = true
  ganttPram.data = row
}


const fetchProductList = async () => {
  loading.value = true
  try {
    const {data} = await api.get('/product/list', {
      params: queryParams.value,
    })

    if (data.code === 200) {
      // 处理进度字段
      productList.value = data.data.list.map((item) => ({
        ...item,
        progress:
            item.amount && item.amount > 0
                ? Number(((item.finishAmount / item.amount) * 100).toFixed(1))
                : 0,
      }))
      // 基于 projectId 去重
      const seen = new Set()
      uniqueProductList.value = productList.value.filter(item => {
        if (seen.has(item.projectId)) return false
        seen.add(item.projectId)
        return true
      })

      const response = await api.get('/project/list', {
        params: queryProParams.value
      })
      projectList.value = response.data.data.list
      Columns.value[0].options = projectList.value.map(item => ({
        label: item.name,
        value: item.id
      }))
      total.value = data.data.total
    } else {
      ElMessage.error(data.message || '获取产品列表失败')
    }
  } catch (error) {
    ElMessage.error('请求失败')
  } finally {
    loading.value = false
  }
}


const handlePageChange = (page) => {
  queryParams.value.pageNum = page
  fetchProductList()
}

const handlePageSizeChange = (size) => {
  queryParams.value.pageSize = size
  queryParams.value.pageNum = 1 // 切换每页条数后，重置为第一页
  fetchProductList()
}

const resetQuery = () => {
  queryParams.value = {
    name: '',
    type: '',
    process: '',
    pageNum: 1,
    pageSize: queryParams.value.pageSize,
  }
  fetchProductList()
}

const openAddDialog = () => {
  currentRow.value = {}
  editDialogVisible.value = true
}

const handleUpdate = (row) => {
  currentRow.value = {...row}
  editDialogVisible.value = true
}

const handleRemove = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除产品【${row.name}】吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    const response = await api.post('/product/delete', {id: row.id});
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      await fetchProductList();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error);
      ElMessage.error('请求失败，请稍后重试');
    }
  }
};

const handleDetail = (row) => {
  // 这里写详情逻辑
}

const handleSave = async (row) => {
  try {
    const url = row.id ? '/product/update' : '/product/add'
    const {data} = await api.post(url, row)
    if (data.code === 200) {
      ElMessage.success(row.id ? '修改成功' : '新增成功')
      editDialogVisible.value = false
      await fetchProductList()
    } else {
      ElMessage.error(data.message || '保存失败')
    }
  } catch (error) {
    ElMessage.error('请求失败，请稍后重试')
  }
}

onMounted(() => {
  fetchProductList()
})


//导入项目相关
const dialogVisible = ref(false)
const uploadRef = ref()
const fileList = ref([])
const selectedFile = ref(null)
const importForm = reactive({
  productType: ''
})

// 上传前校验文件类型
function beforeUpload(file) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  if (!isExcel) {
    ElMessage.error('只能上传 .xlsx 文件')
  }
  return isExcel
}

// 选中文件时保存
function handleFileChange(file) {
  selectedFile.value = file.raw
}

// 点击“确定”上传文件
async function submitImport() {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择一个 Excel 文件')
    return
  }

  const formData = new FormData()
  formData.append('file', selectedFile.value)
  let url = ''

  switch (importForm.productType) {
    case 'HIC':
      url = '/excel/importProDExcelHic'
      break
    case '高硅氧':
      url = '/excel/importProDExcelGgy'
      break
    case '涂层':
      url = '/excel/importProDExcelTc'
      break
    case '结构复材':
      url = '/excel/importProDExcelJgfc'
      break
    case '电气':
      url = '/excel/importProDExcelDq'
      break
    case '力热':
      url = '/excel/importProDExcelLr'
      break
    default:
      throw new Error('不支持的产品类型')
  }
  try {
    const res = await api.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })

    if (res.data.code === 200) {
      ElMessage.success(res.data.data || '导入成功')
      dialogVisible.value = false
      fileList.value = []
      selectedFile.value = null
      await fetchProductList()
    } else {
      ElMessage.error(res.data.message || '导入失败')
    }
  } catch (err) {
    ElMessage.error('导入请求失败，请检查服务器或网络')
  }
}

function downloadTemplate() {
  if (!importForm.productType) {
    ElMessage.warning('请先选择产品类型')
    return
  }
  const type = encodeURIComponent(importForm.productType)
  // 本地接口地址
  const downloadUrl = `http://localhost:8080/excel/downloadProdTemplate?productType=${type}`
  // 如果切换到线上接口也很简单
  // const downloadUrl = `https://pro.lkkj.xyz/excel/downloadProdTemplate?productType=${type}`
  window.open(downloadUrl)
}

</script>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}
</style>
